const { getActionSheet, getDatePicker, getCitySelect, formatTime3 } = require('../../utils/util');
const { getDict } = require('../../utils/dict');

// pages/authentication/components/DefineInput/index.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    placeholder: {
      type: String,
      value: '请输入'
    },
    type: {
      type: String,
      value: 'select'
    },
    errorMsg: {
      type: String,
      value: ''
    },
    label: {
      type: String,
      value: ''
    },
    prop: { type: String, value: 'code' },
    value: {
      type: String | Array | Object,
      observer(newval, oldval) { //  监听数据的变化
        if (newval !== oldval) this.setData({
          value: newval
        })
      }
    },
    dict: { type: String, value: '00' },
    defineList: { type: Boolean, value: false }
  },

  /**
   * 组件的初始数据
   */
  data: {
    show: false,
    actions: [],
  },
  lifetimes: {
    async attached() {
      !this.properties.defineList && this.setData({ actions: await getDict(this.properties.dict) });
    }
  },
  /*** 组件的方法列表 */
  methods: {
    onHideErrorMsg() {
      this.setData({
        errorMsg: ''
      });
    },
    setActions( actions ) {
      this.setData({ actions })
    },
    onOpen() {
      let elem = null;

      switch( this.properties.type ) {
        case "date":
          elem = getDatePicker();
          break;
        case "city":
          elem = getCitySelect();
          break;
        default: 
          elem = getActionSheet();
      }
       
      console.log( elem.open );
      elem && elem.open({ 
        actions: this.data.actions, 
        success: (res) => {
          const d = setResult.call(this, res);
          this.setData({ value: d.name });
          if(this.properties.prop === 'name') {
            this.triggerEvent('select', d.name);
          } else {
            this.triggerEvent('select', d.code);
          }
        }
      });

    },
  }
})

//  处理显示的文本， 并将处理之后的文本进行返回
function setResult( res ) {
  const _res = JSON.parse(JSON.stringify( res ));

  if(this.properties.type === 'date') {
      const text = formatTime3(_res);
      this.setData({ value: text });
  } 
  return _res;
}